import pymongo
import requests
from tools.funciton import get_alpha_token, get_jiwu_token
from config.configs import ALPHA_DB_HOST, ALPHA_DB_PORT, GOAT_ERP_HOST,GOAT_ERP_PORT
from tools.funciton import spuId_to_articleNumber, skuId_to_size, write_xlsx, deal_float

alpha = pymongo.MongoClient(ALPHA_DB_HOST, ALPHA_DB_PORT).alpha
jiwu = pymongo.MongoClient(ALPHA_DB_HOST, ALPHA_DB_PORT).jiwu
korea = pymongo.MongoClient(GOAT_ERP_HOST, GOAT_ERP_PORT).goat_warehouse_korea



def batch_create_stock_out_order(db, merchantCode, warehouseCode, address=" ", expressCompany='京东'):
    """集物批量创建出库单"""
    pipeline = [
        {
            '$match': {
                'warehouseType': "common",
                'qty': {
                    '$ne': 0
                },
                'warehouseCode': warehouseCode,
                'merchantCode': merchantCode,
                # 'skuId': {"$in":[65412613,65412626,603078397,618887629,65412592,618887616,65412631]},
                'status': {"$ne":"repairing"},
                # 'spuId': 18348236,
                'failLevel': {'$ne': 'S'}
            }
        },
        {
            '$project':
                {
                    '_id': 0,
                    'uniqueCode': 1,
                    'spuId': 1,
                    'skuId': 1,
                    'failLevel': 1,
                    'failMemo': 1,
                    'pictures': 1,
                    'outStockPrice': {'$divide': ["$costUnitPrice", 100]},
                    'warehouseCode': 1,
                    'shelves': [
                        {
                            'shelfCode': "$shelfCode",
                            'qty': "$qty"
                        }
                    ]
                }
        }
    ]
    skuList = []
    if db == 'jiwu':
        [skuList.append(i) for i in jiwu.stocks.aggregate(pipeline)]
        param = {
            "type": 3,
            "warehouseCode": warehouseCode,
            "merchantCode": merchantCode,
            "expressInfo": {
                "expressCompany": expressCompany,
                "address": address,
                "payType": "到付"
            },
            "skuList": skuList
        }
        print(skuList)
        url = 'https://erp.geehoop.com/api/backend/stock_out_order/create'
        header = {
            "authorization": f"Bearer {get_jiwu_token()}"}
        r = requests.post(url=url, headers=header, json=param)
        print(r.json())
    elif db == 'alpha':
        [skuList.append(i) for i in alpha.stocks.aggregate(pipeline)]
        param = {
            "type": 3,
            "warehouseCode": warehouseCode,
            "merchantCode": merchantCode,
            "expressInfo": {
                "expressCompany": expressCompany,
                "address": address,
                "payType": "到付"
            },
            "skuList": skuList
        }
        print(skuList)
        url = 'https://alpha.geehoop.com/api/backend/stock_out_order/create'
        header = {
            "authorization": f"Bearer {get_alpha_token()}"}
        r = requests.post(url=url, headers=header, json=param)
        print(r.json())
    else:
        pass


def batch_pick_up(db, outNo):
    """批量完成捡货"""
    if db == 'jiwu':
        li = jiwu.stock_out_orders.find_one({'outStockNo': outNo})['batches']
        for i in range(len(li)):
            li[i]['outQty'] = li[i]['qty']
        jiwu.stock_out_orders.update_one({'outStockNo': outNo}, {"$set": {"batches": li}})
        li1 = jiwu.stock_out_orders.find_one({'outStockNo': outNo})['skuList']
        for i in range(len(li1)):
            li1[i]['shelves'][0]['outQty'] = li1[i]['shelves'][0]['qty']
        for z in li1:
            if 'outQty' not in z['shelves'][0]:
                print(z)
        jiwu.stock_out_orders.update_one({'outStockNo': outNo}, {"$set": {"skuList": li1}})
    elif db == 'alpha':
        li = alpha.stock_out_orders.find_one({'outStockNo': outNo})['batches']
        for i in range(len(li)):
            li[i]['outQty'] = li[i]['qty']
        alpha.stock_out_orders.update_one({'outStockNo': outNo}, {"$set": {"batches": li}})
        li1 = alpha.stock_out_orders.find_one({'outStockNo': outNo})['skuList']
        for i in range(len(li1)):
            li1[i]['shelves'][0]['outQty'] = li1[i]['shelves'][0]['qty']
        for z in li1:
            if 'outQty' not in z['shelves'][0]:
                print(z)
        alpha.stock_out_orders.update_one({'outStockNo': outNo}, {"$set": {"skuList": li1}})
    elif db == 'korea':
        li = korea.stockoutorders.find_one({'outStockNo': outNo})['skuList']
        for i in range(len(li)):
            li[i]['outQty'] = li[i]['qty']
        korea.stockoutorders.update_one({'outStockNo': outNo}, {"$set": {"skuList": li}})


batch_create_stock_out_order("jiwu", "8640", 'CKSH01', " ", '中通')
# batch_pick_up('jiwu', "CK2502246009139")
# update_out_stock_fee('jiwu', 'CK2409106494715', 0.7, 1, 1)
